package modes

import (
	"fmt"
	"time"
)

/*学员收货地址*/
type UserAddress struct {
	Id        int64  `json:"id" xorm:"id"`                 //id
	UId       int64  `json:"uid" xorm:"uid"`               //学员id
	At        int64  `json:"at" xorm:"at"`                 //创建时间
	Name      string `json:"name" xorm:"name"`             //姓名
	Phone     string `json:"phone" xorm:"phone"`           // 手机号
	ProId     int64  `json:"pro_id" xorm:"pro_id"`         //省id
	ProName   string `json:"pro_name" xorm:"pro_name"`     //省名称
	CityId    int64  `json:"city_id" xorm:"city_id"`       //市id
	CityName  string `json:"city_name" xorm:"city_name"`   //市名称
	AreaId    int64  `json:"area_id" xorm:"area_id"`       //区（县）id
	AreaName  string `json:"area_name" xorm:"area_name"`   //区（县）名称
	Detail    string `json:"detail" xorm:"detail"`         //详细地址
	IsDefault int64  `json:"is_default" xorm:"is_default"` //设置为默认地址 1默认
}

func (this *UserAddress) TableName() string {
	return "user_address"
}
func (this *UserAddress) Save() (int64, error) {
	this.At = time.Now().Unix()
	i, e := Db(0).Insert(this)
	return i, e
}

func (this *UserAddress) Get() (bool, error) {
	return Db(0).Get(this)
}
func (this *UserAddress) update(where string, field string) (int64, error) {
	return Db(0).Where(where).Cols(field).Update(this)
}
func (this *UserAddress) delete(where string) (int64, error) {
	return Db(0).Where(where).Delete(this)
}
func (this *UserAddress) Del() (int64, error) {
	if this.Id == 0 {
		return 100, nil
	}

	i, err := this.delete("")
	return i, err
}

func (this *UserAddress) Update() error {
	_, err := this.update(fmt.Sprintf("id=%d", this.Id), "name,phone,pro_id,pro_name,city_id,city_name,area_id,area_name,detail,is_default,at")
	return err
}

func (this *UserAddress) List(where string) ([]UserAddress, error) {
	list := make([]UserAddress, 0)
	err := Db(0).Where(where).Asc("is_default").Desc("at").Find(&list)
	return list, err
}

// 设置地址为非默认
func (this *UserAddress) ClearIsDefault() error {
	address := UserAddress{
		UId:       this.UId,
		IsDefault: 2,
	}
	_, err := Db(0).Table("user_address").Where(fmt.Sprintf("uid=%d", this.UId)).Update(address)
	return err
}

// 设置地址为默认
func (this *UserAddress) SetIsDefault() error {
	err := this.ClearIsDefault()
	if err != nil {
		return err
	}
	_, err = Db(0).Where(fmt.Sprintf("id=%d", this.Id)).Update(&this)
	return err
}
